package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	//bad()

	ok()
}

func bad() {
	var m map[int]int = make(map[int]int)
	m[1] = 1
	for i := 0; i < 10; i++ {
		go func() {
			m[i]++ //fatal error: concurrent map writes
		}()
	}

	<-time.After(time.Second)
	fmt.Println(m[1])
}

func ok() {
	var m sync.Map
	m.Store(1, 1)
	for i := 0; i < 10; i++ {
		go func() {
			for {
				v, _ := m.Load(1)
				done := m.CompareAndSwap(1, v, v.(int)+1)
				if done {
					fmt.Println("done")
					break
				}
			}
		}()
	}

	<-time.After(time.Second)
	v, _ := m.Load(1)
	fmt.Println(v)
}
